<?php

include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/header.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/comp.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/fcs.php');
?>
<script type="text/javascript">

function calc(frm)
{
	
//	document.addform.amount.value=(document.addform.quantity.value*document.addform.rate.value)+(document.addform.add.value*1)-(document.addform.less.value*1);
	//document.addform.amount.focus();
	var bales=frm.bale_no.value.split(",");
	var qs=frm.quantity.value.split(",");
	var rates=frm.rate.value.split(",");	
	
	if(bales.length!=qs.length || bales.length!=rates.length || qs.length!=rates.length)
	{
		alert("Error in Bale No, Quantity and Rates Sequence Match!");
		frm.bale_no.focus();
	}
	else
	{
		var sum=0;
		for(i=0;i<bales.length;i++)
		{
			sum+=qs[i]*rates[i];
		}
		frm.amount.value=Math.round(sum+(frm.add.value*1)-(frm.less.value*1)); 
		frm.amount.focus();
	}
		
		
}

function expand_bno(frm)
{
	
	var bales=frm.bale_no.value;
	
	if(bales.search("-"))
	{
		bales=frm.bale_no.value.split("-");
		//now bales is an array
	
		for(i=0;i<bales.length-1;i++)
		{
			temp1=bales[i].split(",");
			temp2=bales[i+1].split(",");
		
			var start=parseInt(temp1[temp1.length-1]);
			var limit=parseInt(temp2[0]);
			
			for(j=start+1;j<limit;j++)
			{
				bales[i]+=",";
				bales[i]+=j;

			}
		
		}
		frm.bale_no.value=bales.toString();
	}
	


}

function expand_quantity(frm)
{
	
	var quantity=frm.quantity.value;
	
	if(quantity.search("x"))
	{
		quantity=frm.quantity.value.split(",");
		//now bales is an array
	
		for(i=0;i<quantity.length;i++)
		{
			if(quantity[i].search("x"))
			{
				temp=quantity[i].split("x");
				temp[1]=parseInt(temp[1]);
				value=temp[0];
				for(j=1;j<temp[1];j++)
				{
					temp[0]+=",";
					temp[0]+=value;
				}
				
				quantity[i]=temp[0];
			}
			
		
		}
		frm.quantity.value=quantity.toString();
	}
	


}

function expand_rate(frm)
{
	
	var rate=frm.rate.value;
	
	if(rate.search("x"))
	{
		rate=frm.rate.value.split(",");
		//now bales is an array
	
		for(i=0;i<rate.length;i++)
		{
			if(rate[i].search("x"))
			{
				temp=rate[i].split("x");
				temp[1]=parseInt(temp[1]);
				value=temp[0];
				for(j=1;j<temp[1];j++)
				{
					temp[0]+=",";
					temp[0]+=value;
				}
				
				rate[i]=temp[0];
			}
			
		
		}
		frm.rate.value=rate.toString();
	}
	


}

</script>

<?php

/* INDEF GROUPING...
FUNCTION EXTRACT_LEDGER($ID)
{
	 ADD ALL "LEDGERS" UNDER $ID;
	 LIST= SELECT ALL "GROUP" UNDER $ID;
	 WHILE(LIST!=NULL)
	 {
	 	EXTRACT_LEDGER($ID[LIST])
		LIST++;
	}
	RETURN;
}

*/


if(isset($_GET['task']))
{
	if(!$link=mysql_connect("localhost",$user,$pass))
		die("Error in Database Connection");

	if(!mysql_select_db("bs"))
		echo("Error in Database Selection");

	if($_GET['task']=="addform")
	{
?>

		| <a href="trans.php">Transaction </a> | Purchase Book</div>
		<h3>Purchase Book Entry</h3>
		<table cellpadding="3" class="main">
		<form name="addform" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
		<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo date("d-m-Y");?>" /></td></tr>
		<tr><td><label>Bill No</label></td><td> <input type="text" name="bill_no" size="20"/></td></tr>
		
		<tr><td><label>Party A/C</label> </td><td><select name="ldname">
									<?php 		
//sundry debtors				
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Sundry Debtors'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
//sundry creditors
								$result=mysql_query("select * from bs_groups where gpname='Sundry Creditors'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Party Ledgers First</option>");
								
								?>
								</select>
								 </td></tr>
		<tr><td><label>Bale No</label></td><td><input type="text" name="bale_no" size="42" onblur="expand_bno(this.form)" /></td></tr>
<span id="placeholder">
		<tr><td><label>L/R No</label></td><td><input type="text" name="lr_no" size="10" /></td></tr>
</span>		
		<tr><td><label>Description</label></td><td><textarea name="desc" cols="30" rows="4"></textarea></td></tr>
		<tr><td><label>Quantity</label></td><td><input type="text" name="quantity" value="0" size="42" onblur="expand_quantity(this.form)" /> Unit</td></tr>		
		<tr><td><label>Rates</label></td><td><input type="text" name="rate" value="0" size="42" onblur="expand_rate(this.form)"/> per Unit</td></tr>				
		<tr><td><label>Add</label></td><td><input type="text" name="add" value="0" /> Rs</td></tr>										 
		
<?php /*		<tr><td><label>Ledger</label> </td><td><select name="addldname"> DEPRECATED...........CANT BE USEFUL LATER
												<option value="nothing">Select...</option>
								 		
//direct income ledger
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Direct Income'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
//indirect income ledger
								$result=mysql_query("select * from bs_groups where gpname='Indirect Income'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Income Ledgers First</option>");
								
								
								</select>
								 </td></tr>*/ ?>

		<tr><td><label>Less</label></td><td><input type="text" name="less" value="0" /> Rs</td></tr>										 
<?php /*		<tr><td><label>Ledger</label> </td><td><select name="lessldname">
								<option value="nothing">Select...</option>
						
//direct income ledger
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Direct Expense'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
//indirect income ledger
								$result=mysql_query("select * from bs_groups where gpname='Indirect Expense'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Expense Ledgers First</option>");
								
								
		
								</select>
								 </td></tr> */?>
		
		<tr><td><label>Nett Amount</label></td><td><input type="text" name="amount" value="0" onfocus="calc(this.form)" /> Rs</td></tr>										 		
		<tr><td><label>Purchase Ledger</label> </td><td><select name="pldname">
									<?php 		
//Purchase account				
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Purchase Account'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);

		
								if($count==0)
									echo ("<option value='nothing'>Create Purchase Ledgers First</option>");

								
								?>
								</select>
								 </td></tr>
								 
		
		
		
		
		<tr><td><input type="submit" value="Add" /></td></tr>
		<input type="hidden" name="task" value="add" />
		</form>
		</table>
			
		
<?php
	}//end of add form
	if($_GET['task']=="edit_form")
	{
		$pid=$_GET['pid'];

		$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_purchase_book where id='{$pid}'");
		if(!$result)
				echo("Error in Query Execution");
		$arr=mysql_fetch_array($result);
		
		$bill_no=$arr['bill_no'];
		$ldid=$arr['ledger_id'];
		$bale_no=$arr['bale_no'];		
		$lr_no=$arr['lr_no'];				
		$description=$arr['description'];
		$quantity=$arr['quantity'];
		$rate=$arr['rate'];
		$add=(int)$arr['add'];
		$less=(int)$arr['less'];
		$amount=(int)$arr['amount'];
		$pldid=$arr['purchase_ledger_id'];		
		$date=$arr['date'];
		
		
									
	
	
?>

		| <a href="trans.php">Transaction </a> | Purchase Book	</div>
		<h3>Edit Purchase Book Entry | <a href="pbook_trans.php?task=delete&pid=<?php echo $pid?>">Delete</a></h3>
		<table cellpadding="3" class="main">
		<form name="edit_addform" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
		<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo $date?>" /></td></tr>
		<tr><td><label>Bill No</label></td><td> <input type="text" name="bill_no" size="20" value="<?php echo $bill_no?>" /></td></tr>
		
		<tr><td><label>Party A/C</label> </td><td><select name="ldid">
									<?php 		
//sundry debtors				
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Sundry Debtors'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger_with_choice($arr['id'],$ldid);
//sundry creditors
								$result=mysql_query("select * from bs_groups where gpname='Sundry Creditors'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger_with_choice($arr['id'],$ldid);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Party Ledgers First</option>");
								
								?>
								</select>
								 </td></tr>
		<tr><td><label>Bale No</label></td><td><input type="text" name="bale_no" size="42" onblur="expand_bno(this.form)" value="<?php echo $bale_no?>" /></td></tr>
<span id="placeholder">
		<tr><td><label>L/R No</label></td><td><input type="text" name="lr_no" size="10" value="<?php echo $lr_no?>" /></td></tr>
</span>		
		<tr><td><label>Description</label></td><td><textarea name="desc" cols="30" rows="4"><?php echo $description?></textarea></td></tr>
		<tr><td><label>Quantity</label></td><td><input type="text" name="quantity" value="<?php echo $quantity?>" size="42" onblur="expand_quantity(this.form)" /> Unit</td></tr>		
		<tr><td><label>Rates</label></td><td><input type="text" name="rate" value="<?php echo $rate?>"size="42" onblur="expand_rate(this.form)"/> per Unit</td></tr>				
		<tr><td><label>Add</label></td><td><input type="text" name="add" value="<?php echo $add?>" /> Rs</td></tr>										 
		
<?php /*		<tr><td><label>Ledger</label> </td><td><select name="addldname"> DEPRECATED...........CANT BE USEFUL LATER
												<option value="nothing">Select...</option>
								 		
//direct income ledger
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Direct Income'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
//indirect income ledger
								$result=mysql_query("select * from bs_groups where gpname='Indirect Income'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Income Ledgers First</option>");
								
								
								</select>
								 </td></tr>*/ ?>

		<tr><td><label>Less</label></td><td><input type="text" name="less" value="<?php echo $less?>" /> Rs</td></tr>										 
<?php /*		<tr><td><label>Ledger</label> </td><td><select name="lessldname">
								<option value="nothing">Select...</option>
						
//direct income ledger
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Direct Expense'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
//indirect income ledger
								$result=mysql_query("select * from bs_groups where gpname='Indirect Expense'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger($arr['id']);
									
		
								if($count==0)
									echo ("<option value='nothing'>Create Expense Ledgers First</option>");
								
								
		
								</select>
								 </td></tr> */?>
		
		<tr><td><label>Nett Amount</label></td><td><input type="text" name="amount" value="<?php echo $amount?>" onfocus="calc(this.form)" /> Rs</td></tr>										 		
		<tr><td><label>Purchase Ledger</label> </td><td><select name="pldid">
									<?php 		
//Purchase account				
								$count=0;
								$result=mysql_query("select * from bs_groups where gpname='Purchase Account'");
								if(!$result)
									echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
								extract_ledger_with_choice($arr['id'],$pldid);

		
								if($count==0)
									echo ("<option value='nothing'>Create Purchase Ledgers First</option>");

								
								?>
								</select>
								 </td></tr>
								 
		
		
		
		
		<tr><td><input type="submit" value="Update" /></td></tr>
		<input type="hidden" name="pid" value="<?php echo $pid ?>" />		
		<input type="hidden" name="task" value="edit_add" />
		</form>
		</table>
			
		
<?php
	}//end of edit form
	if($_GET['task']=="delete")
	{
?>
	| <a href="trans.php">Transaction </a> | Purchase Book</div>
		<h3>Purchase Book Transaction Deletion</h3>

<?php	
		$succ=1;
		
		$pid=$_GET['pid'];

		$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_purchase_book where id='{$pid}'");
		if(!$result)
				echo("Error in Query Execution");
		$previous=mysql_fetch_array($result);
		
		
		
		//delete in ledger_id

					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$ldname} where voucher_type='PURCHASE' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$ldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				

		
		//delete in purchase_ledger_id
		
					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['purchase_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$pldname} where voucher_type='PURCHASE' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				
		
		//delete in purchase book
						$result=mysql_query("delete from bs_purchase_book where id='{$pid}'" );			
						if(!$result)
						{
							echo("Error in purchase book deletion".mysql_error());
							$succ=0;
						}
			
		if($succ==1)
			echo"<br>SuccessFul";
		else
			echo"<br>Operation Fail";
			
				
	}
	
}
else if(isset($_POST['task']))
{
	if(!$link=mysql_connect("localhost",$user,$pass))
		die("Error in Database Connection");

	if(!mysql_select_db("bs"))
		echo("Error in Database Selection");

?>
		| <a href="trans.php">Transaction </a> | Purchase Book	</div>
		<h3>Purchase Book Entry</h3>

<?php
		$valid=1;
		$arr=explode("-",$_POST['date']);
		if(!ereg("^[0-3]?[0-9][\./\-][0-1]?[0-9][\./\-]20[0-9][0-9]$",$_POST['date']) or !checkdate($arr[1],$arr[0],$arr[2]))
		{
			echo "Check Your Input Date<br>";
			$valid=0;
		}
		else
			$date=date("Y-m-d",mktime(0,0,0,$arr[1],$arr[0],$arr[2]));
		
		if(empty($_POST['bale_no']) or empty($_POST['lr_no']) or !ereg("^[0-9]+(.([0-9]){2,2})?$",$_POST['amount']) or !ereg("^[0-9]+$",$_POST['add']) or !ereg("^[0-9]+$",$_POST['less']) or ($amount=(int)$_POST['amount'])==0 )
		{
			echo "Check Your Input<br>";
			$valid=0;
		}
		
		
		if(!ereg("^[a-zA-Z0-9 \_,]+$",$_POST['bale_no']) or !ereg("^[a-zA-Z0-9 \_,]+$",$_POST['lr_no']) or !ereg("^[a-zA-Z0-9 \_,]+$",$_POST['bill_no']))
		{
			echo "<br>Special Characters are not allowed in Input Name except '_' and ','";
			$valid=0;
		}
		
		//bill no repetition check range.	
		if($arr[1]>=4)
		{
			$check_from_date=$arr[2]."-04-01";
			$check_to_date=($arr[2]+1)."-03-31";
		}
		else
		{
			$check_from_date=($arr[2]-1)."-04-01";
			$check_to_date=($arr[2])."-03-31";
		}

		//checking for duplicate ledger_id+bill_no in purchase book becuase i will treat this as a KEY.
	if($_POST['task']!="edit_add")
	{
		$result=mysql_query("select bill_no,ldname from bs_purchase_book,bs_ledgers where ledger_id=bs_ledgers.id and bill_no='{$_POST['bill_no']}' and ldname='{$_POST['ldname']}' and date>='{$check_from_date}' and date<='{$check_to_date}'");
		if(!$result)
			echo("Error in Query Execution");
			
		if($arr=mysql_fetch_array($result))
		{
			echo("<br>Duplicate Bill No:<b> {$_POST['bill_no']}</b>  For Ledger:<b> {$_POST['ldname']}</b><br>");
			$valid=0;
		}
			
	}
	else
	{
		//next time : must use ldid and pldid 
		$pid=$_POST['pid'];
		$result=mysql_query("select bill_no from bs_purchase_book where bill_no='{$_POST['bill_no']}' and ledger_id='{$_POST['ldid']}' and id<>'{$pid}' and date>='{$check_from_date}' and date<='{$check_to_date}'");
		if(!$result)
			echo("Error in Query Execution");
			
		if($arr=mysql_fetch_array($result))
		{
			echo("<br>Duplicate Bill No:<b> {$_POST['bill_no']}</b>  For Ledger <br>");
			$valid=0;
		}
	}

	
	if($_POST['task']=="add")
	{
		
		$succ=0;
		if($valid==1)
		{
			$succ=1;
			$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['ldname']}'");
			if(!$result)
			{
				echo("Error in Query Execution");
				$succ=0;
			}
			$arr=mysql_fetch_array($result);
			
			$ldid=$arr['id'];
			
			$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['pldname']}'");
			if(!$result)
			{
				echo("Error in Query Execution");
				$succ=0;
			}
			$arr=mysql_fetch_array($result);
			
			$pldid=$arr['id'];
					
		
				
			//insert into purchase book
			
			$result=mysql_query("INSERT INTO `bs_purchase_book` (`id`, `bill_no`, `ledger_id`,`bale_no`, `lr_no`, `description`, `quantity`, `rate`, `add`, `less`, `amount`, `date`, `purchase_ledger_id`) VALUES (NULL,'{$_POST['bill_no']}' ,'{$ldid} ','{$_POST['bale_no']}','{$_POST['lr_no']}','{$_POST['desc']}','{$_POST['quantity']}','{$_POST['rate']}','{$_POST['add']}','{$_POST['less']}','{$_POST['amount']}','{$date}','{$pldid}')");
			if(!$result)
			{
				echo("Error in Purchase Book Insertion");
				$succ=0;
			}
			
			
			$voucherid=mysql_insert_id();
			//debit purchase ledger
			$pldname="bs_ledger_".ereg_replace(" ","_",$_POST['pldname']);
			$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PURCHASE','{$voucherid}', '{$_POST['amount']}','0.00','{$date}')");			
			if(!$result)
			{
				echo("<br>Error in Purchase Ledger Insertion:".mysql_error());
				$succ=0;
			}
			

			//credit party ledger
			$ldname="bs_ledger_".ereg_replace(" ","_",$_POST['ldname']);
			$result=mysql_query("INSERT INTO {$ldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PURCHASE','{$voucherid}', '0.00','{$_POST['amount']}','{$date}')");			
			if(!$result)
			{
				echo("Error in Party Ledger Insertion".mysql_error());
				$succ=0;
			}
			
			
		}
		
	}//end of add

	if($_POST['task']=="edit_add")
	{
		/*
			if there is any change
			{
				update purchase book..			
				if change in ldid
				{
					delete from previous ldid
					entry in new ldid
				}
				else
				{
					//no change in ldid
					//but there is another change
					so update in ldid
				}
			
				if change in pldid
				{
					delete from previous pldid
					entry in new pldid
				}
				{
					//no change in pldid
					//but there is another change
					so update in  pldid
				}
				
				
			}
		*/
		
		//checking if there is any change				
		$pid=$_POST['pid'];

		$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_purchase_book where id='{$pid}'");
		if(!$result)
				echo("Error in Query Execution");
		$previous=mysql_fetch_array($result);

		$change=1;
		
		if($previous['bill_no']==$_POST['bill_no'])
		{
	
			if($previous['ledger_id']==$_POST['ldid'])
			{
			
				if($previous['bale_no']==$_POST['bale_no'])
				{
				
					if($previous['lr_no']==$_POST['lr_no'])
					{
					
						if($previous['description']==$_POST['desc'])
						{
						
							if($previous['quantity']==$_POST['quantity'])
							{
								
								if($previous['rate']==$_POST['rate'])
								{
									if((int)$previous['add']==$_POST['add'])
									{
										if((int)$previous['less']==$_POST['less'])
										{
											if((int)$previous['amount']==$_POST['amount'])
											{
												if($previous['date']==$_POST['date'])
												{
													if($previous['purchase_ledger_id']==$_POST['pldid'])
													{	
														$change=0;
														echo "No Alteration Performed!";
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
														
			
		
		$succ=0;
//		$valid=0;//temp
		if($valid==1 and $change==1)
		{
			//we are here it means...there is any change
			$succ=1;
			//update purchase book.
			$pid=$_POST['pid'];
			$ldid=$_POST['ldid'];
			$pldid=$_POST['pldid'];		
			
			//same query again! must be global 

			$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_purchase_book where id='{$pid}'");
			if(!$result)
					echo("Error in Query Execution");
			$previous=mysql_fetch_array($result);
			
			$result=mysql_query("UPDATE `bs_purchase_book` as p SET p.bill_no='{$_POST['bill_no']}', p.ledger_id = '{$ldid}',p.bale_no='{$_POST['bale_no']}', p.lr_no='{$_POST['lr_no']}', p.description='{$_POST['desc']}', p.quantity='{$_POST['quantity']}', p.rate='{$_POST['rate']}' , p.add='{$_POST['add']}', p.less='{$_POST['less']}', p.amount='{$_POST['amount']}' , p.date='{$date}',p.purchase_ledger_id='{$pldid}' WHERE p.id = '{$pid}' ");
			if(!$result)
			{
				echo("Error in Purchase Alteration : ".mysql_error());
				$succ=0;
			}
					

			
			
			
			if($previous['ledger_id']!=$ldid)
			{
				//delete in one-------add in another
				
				
				//delete from previous
					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$ldname} where voucher_type='PURCHASE' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$ldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				
					
				//add in new (credit party ledger)
					//1. extract new ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$ldid}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
					//2. insert in new 
					//credit party ledger
					$result=mysql_query("INSERT INTO {$ldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PURCHASE','{$pid}', '0.00','{$_POST['amount']}','{$date}')");			
					if(!$result)
					{
							echo("Error in Party Ledger Insertion".mysql_error());
							$succ=0;
					}
					

					
			}
			else
			{
					//update in one
					
					//1. extract previous=new ldname (credited)
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
					$result=mysql_query("UPDATE {$ldname} as p SET p.credit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='PURCHASE' and p.voucher_id = '{$pid}' LIMIT 1 ");
					if(!$result)
					{
						echo("Error in Credited Alteration");
						$succ=0;
					}
		
			}
			
			if($previous['purchase_ledger_id']!=$pldid)
			{
				//delete in one-------add in another
				//delete from previous
					//1. extract previous pldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['purchase_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
					//2. delete from previous ldname
					//first fetch the id!!!

						$result=mysql_query("select id from {$pldname} where voucher_type='PURCHASE' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);

						$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				
									
					
				//add in new (credit party ledger)
					//1. extract new pldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$pldid}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
					//2. insert in new 
					//debit purchase ledger
					$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PURCHASE','{$pid}','{$_POST['amount']}', '0.00','{$date}')");			
					if(!$result)
					{
							echo("Error in Party Ledger Insertion".mysql_error());
							$succ=0;
					}
					
				
					
			}
			else
			{
				//update in one
					//1. extract previous=new pldname (debited)
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['purchase_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
					$result=mysql_query("UPDATE {$pldname} as p SET p.debit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='PURCHASE' and p.voucher_id = '{$pid}' LIMIT 1 ");
					if(!$result)
					{
						echo("Error in Debited Alteration");
						$succ=0;
					}
				
			}
			
				
		
			
		}
		
	}//end of edit add
	
	if($succ==1)
		echo"<br>SuccessFul";
	else
		echo"<br>Operation Fail";


		
}


include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/footer.inc');
?>



